package com.feixiang.feixiangagent.chatmemory;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.feixiang.feixiangagent.proxy.MessageConverter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
/**
 * Redis 实现的 ChatMemory 类，用于存储对话
 */
public class RedisChatMemory implements ChatMemory {
    private static final String KEY_PREFIX = "chat:history:";
    private final RedisTemplate<String, Object> redisTemplate;
    private final ListOperations<String, Object> listOperations;

    public RedisChatMemory(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.listOperations = redisTemplate.opsForList();
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        if (messages == null || messages.isEmpty()) {
            return;
        }
        String key = getKey(conversationId);
        // 将 Message 对象转换为 Map 再存储
        List<Object> serializedMessages = messages.stream()
                .map(MessageConverter::toSerializableMap)
                .collect(Collectors.toList());
        listOperations.rightPushAll(key, serializedMessages);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = getKey(conversationId);
        Long size = listOperations.size(key);
        if (size == null || size == 0) {
            return Collections.emptyList();
        }
        long start = Math.max(0, size - lastN);
        long end = size - 1;
        // 从 Redis 获取 Map 列表并转换回 Message 对象
        List<Object> storedObjects = listOperations.range(key, start, end);
        return storedObjects.stream()
                .filter(obj -> obj instanceof Map)
                .map(obj -> (Map<String, Object>) obj)
                .map(MessageConverter::fromSerializableMap)
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        redisTemplate.delete(getKey(conversationId));
    }

    private String getKey(String conversationId) {
        return KEY_PREFIX + conversationId;
    }
}